#!/usr/bin/python3.7
# # Aljaz Blatnik
# # november 2019
# # LSO IKT
#import matplotlib
#import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
import math
import re
from collections import ChainMap

# pazi to samo ustvari celice! Za preracun je kodirano v sami kodi!
Nrows = 20
Ncols = 5
cellre = re.compile(r'\b[A-Z][0-9]\b')

def cellname(i, j):    
    return f'{chr(ord("A")+j)}{i+1}'

def phase_unwrap(in_array):    
    # razvijemo zasuk faze pri meritvah -180 / +180    
    length = len(in_array)    
    dp = np.diff(in_array,1)
    dps = np.mod(dp+180,360)-180    
    dps[(dps==-180)&(dp>0)] = 180    
    dp_corr = dps-dp    
    dp_corr[np.abs(dp)<180] = 0    
    in_array[1:length] = in_array[1:length] + np.cumsum(dp_corr)    
    in_array = [x - in_array[0] for x in in_array]    
    in_array = [np.abs(x) for x in in_array]    
    return in_array
    
class Cell():    
    # razred celice - ustvarjanje in preracunavanje vrednosti
    def __init__(self, i, j, siblings, parent):        
        self.row = i        
        self.col = j        
        self.siblings = siblings        
        self.name = cellname(i, j)        
        self.formula = '0'        
        self.value = 0        
        self.width = 10        
        self.deps = set()        
        self.reqs = set()        
        self.var = tk.StringVar()        
        entry = self.widget = tk.Entry(parent,
                                       textvariable=self.var,                                       
                                       justify='center',                                       
                                       width=15)        
        entry.bind('<FocusIn>', self.edit)        
        entry.bind('<FocusOut>', self.update)        
        entry.bind('<Return>', self.move(+1, 0))        
        entry.bind('<Up>', self.move(-1, 0))        
        entry.bind('<Down>', self.move(+1, 0))        
        entry.bind('<Left>', self.move(0, -1))        
        entry.bind('<Right>', self.move(0, 1))        
        self.var.set(self.value)    
    
    def move(self, rowadvance, coladvance):        
        targetrow = (self.row + rowadvance) % Nrows        
        targetcol = (self.col + coladvance) % Ncols        
        
    def focus(event):           
        targetwidget = self.siblings[cellname(targetrow, targetcol)].widget            
        targetwidget.focus()        
        return focus    
    
    def calculate(self):        
        # do nothing        
        return    
        
    def propagate(self):        
        for d in self.deps:            
            self.siblings[d].calculate()            
            self.siblings[d].propagate()    
        
    def edit(self, event):        
        self.var.set(self.formula)        
        self.widget.select_range(0, tk.END)    
        
    def update(self, event):        
        self.formula = self.var.get()        
        self.calculate()        
        self.propagate()        
        if hasattr(event, 'keysym') and event.keysym == "Return":            
            self.var.set(self.formula)
            
class SpreadSheet(tk.Frame):    
            
    def __init__(self, rows, cols, master=None):        
        super().__init__(master)        
        self.rows = rows        
        self.cols = cols        
        self.cells = {}        
        self.pack()        
        self.create_widgets()    
        
    def create_widgets(self):        
        # Okvir za celice        
        self.cellframe = tk.Frame(self)        
        self.cellframe.pack(side='top')        
        # Odmik za napise stolpcev        
        blank = tk.Label(self.cellframe)        
        blank.grid(row=0, column=0)       
        # razdalja        l
        label = tk.Label(self.cellframe, text="Razdalja [cm]")        
        label.grid(row=0, column=1)        
        # Amplituda 1 [dB]        
        label = tk.Label(self.cellframe, text="Amplituda 1 [dB]")        
        label.grid(row=0, column=2)        
        # Kot 1 [°]        
        label = tk.Label(self.cellframe, text="Kot 1 [°]")        
        label.grid(row=0, column=3)        
        # Amplituda 2 [dB]        
        label = tk.Label(self.cellframe, text="Amplituda 2 [dB]")        
        label.grid(row=0, column=4)        
        # Kot 2 [°]        
        label = tk.Label(self.cellframe, text="Kot 2 [°]")        
        label.grid(row=0, column=5)        
        # Dodamo vrstice        
        for i in range(self.rows):            
            rowlabel = tk.Label(self.cellframe, text=str(i + 1))            
            rowlabel.grid(row=1+i, column=0, sticky='e')            
            for j in range(self.cols):                
                cell = Cell(i, j, self.cells, self.cellframe)                
                self.cells[cell.name] = cell                
                cell.widget.grid(row=1+i, column=1+j)        
                
        button_upload = tk.Button(self.cellframe, text="Uvozi podatke", width=15, command=buttonPressed, state="disabled")        
        button_upload.grid(row=22,column=1,columnspan=5,ipadx=0,ipady=0,padx=5,pady=5, sticky="w")        
        button_generate = tk.Button(self.cellframe, text="Izračunaj", width=25, bg="#11ac0a", command=buttonPressed)        
        button_generate.grid(row=22,column=1,columnspan=5,ipadx=0,ipady=0,padx=5,pady=5)        
        button_save = tk.Button(self.cellframe, text="Shrani podatke", width=15, command=buttonPressed, state="disabled")        
        button_save.grid(row=22,column=1,columnspan=5,ipadx=0,ipady=0,padx=5,pady=5, sticky="e")
        
def buttonPressed():    
    x_axis = [0 for x in range(20)]    
    y_axis_amplitude = [0 for x in range(20)]    
    y_axis_phase = [0 for x in range(20)]    
    phase_1 = [0 for x in range(20)]    
    phase_2 =[0 for x in range(20)]    
    print("Preracunavam vrednosti ...")    
    # Pridobi / izracunaj podatke 1/2    
    for i in range(20):        
        x_axis[i] = float(app.cells["A"+str(i+1)].var.get().replace(',','.'))        
        pwr_1 = 10**(float(app.cells["B"+str(i+1)].var.get().replace(',','.'))/10)        
        pwr_2 = 10**(float(app.cells["D"+str(i+1)].var.get().replace(',','.'))/10)        
        y_axis_amplitude[i] = 10 * math.log10((pwr_1+pwr_2)/2)        
        phase_1[i] = float(app.cells["C"+str(i+1)].var.get().replace(',','.'))        
        phase_2[i] = float(app.cells["E"+str(i+1)].var.get().replace(',','.'))    
    phase_1 = phase_unwrap(phase_1)    
    phase_2 = phase_unwrap(phase_2)    
    # Izracunaj podatke 2/2    
    for i in range(20):        
        y_axis_phase[i] = (phase_1[i] + phase_2[i])/2        
        print(str(i+1) + " - " + str(x_axis[i]) + "cm: " + str(round(y_axis_amplitude[i],2)) + "dBm, " + str(y_axis_phase[i]) + "°")    
    
    #print("Risem graf ...")    
    # #fig, ax = plt.subplots()    
    # #ax.plot(x_axis, y_axis_amplitude)    
    # #ax.set(xlabel='Razdalja [cm]', ylabel='Moc [dBm]')    
    # #ax.grid()    
    # #plt.show()  
  
root = tk.Tk()
root.title("Fazni potek vzbujanja Yagi antene")
root.resizable(False, False)
app = SpreadSheet(Nrows, Ncols, master=root)
app.mainloop()